﻿$(document).ready(function() {
    var studiesIndexVm = new StudiesIndexVm();
    ko.applyBindings(studiesIndexVm, document.getElementById("body"));
});

var StudiesIndexVm = function() {
    var self = this;
    BaseVm.call(self);

    self.ActiveStudy = ko.observable();
    self.Studies = ko.observableArray([]);

    self.IsInitialized.subscribe(function(isDone) {
        if (isDone) {
            self.GetAllStudies();
        }
    });

    self.GetAllStudies = function() {
        self.GetData("/Studies/GetAllStudies").done(
            function(data) {
                self.Studies.removeAll();
                var parsedJson = JSON.parse(data);
                for (var i = 0; i < parsedJson.length; i++) {
                    var studyVm = new StudyVm(parsedJson[i]);
                    self.Studies.push(studyVm);
                }
                if (self.Studies().length > 0)
                    self.AuditReasonSelector().GetAuditReasonsByAuditTypeId(self.Studies()[0].AuditTypeId());
            });
    };

    self.AddStudy = function() {
        var studyVm = new StudyVm();
        self.Studies.push(studyVm);
        self.EditStudy(studyVm);
    };

    self.EditStudy = function(study) {
        self.ActiveStudy(study);
    };

    self.IsStudyBeingEdited = function (study) {
        return study == self.ActiveStudy();
    };

    self.Cancel = function(study) {
        study.DirtyFlag.reset();
        self.ActiveStudy(null);

        if (study.IsNew())
            self.Studies.remove(study);
    };

    self.IsStudyValid = function(study) {
        var result = ko.validation.group(study);

        if (!study.isValid()) {
            result.showAllMessages(true);
            return false;
        }
        if (!study.DirtyFlag.isDirty()) {
            alert('No changes were made.');
            return false;
        }
        if (self.DuplicateSponsorAndProtocolExists()) {
            alert('A study with that sponsor and protocol already exists in the system.');
            return false;
        }
        return true;
    };

    self.SaveStudy = function(study) {
        if (!self.IsStudyValid(study))
            return;

        self.PromptForAuditReasonThenPostToServerAndRefreshViewModel("/Studies/SaveStudy", study, null, false)
            .done(function(data) {
                study.DirtyFlag.update();
                self.ActiveStudy(false);
            });
    };

    self.DuplicateSponsorAndProtocolExists = function() {
        var activeStudy = self.ActiveStudy();
        var matchExists = ko.utils.arrayFirst(self.Studies(), function(study) {
            return study != activeStudy && study.Protocol().toLowerCase() == activeStudy.Protocol().toLowerCase() && study.Sponsor().toLowerCase() == activeStudy.Sponsor().toLowerCase();
        });
        return (matchExists);
    };

};